package yunjiao.javatutorials.lang.concurrent.interrupt;

import java.util.concurrent.*;

/**
 * 使用 ExecutorService 的中断处理
 *
 * @author yangyunjiao
 */
public class ExecutorInterruptExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<?> future = executor.submit(new CallableTask());

        try {
            // 等待任务完成，设置超时时间
            future.get(3, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            System.out.println("任务超时，尝试取消");
            future.cancel(true); // 中断任务
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }

    static class CallableTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            try {
                for (int i = 0; i < 10; i++) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("任务被取消");
                        return "任务被中断";
                    }
                    System.out.println("处理第 " + i + " 个项目");
                    Thread.sleep(1000);
                }
                return "任务完成";
            } catch (InterruptedException e) {
                System.out.println("任务执行中被中断");
                throw e; // 重新抛出异常
            }
        }
    }
}
